package com.tomcov.server;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.tomcov.client.service.MessageService;
import com.tomcov.shared.Message;

public class MessageServiceImpl extends RemoteServiceServlet implements MessageService{

	private static final long serialVersionUID = 1L;

	@Override
	public Message AddMessage(Message message) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(message);
			return message;
		} finally {
			pm.close();
		}
	}

	@Override
	public List<Message> getMessageTo(String User) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query= pm.newQuery(com.tomcov.shared.Message.class);
		query.setFilter("From == userNameParam && deleteto == deletefromParam");
		query.setOrdering("date desc");
		query.declareParameters("String userNameParam, String deletefromParam");
		try{
			@SuppressWarnings("unchecked")
			List<Message> results = (List<Message>) query.execute(User,"false");
			return (List<Message>) pm.detachCopyAll(results);

		}
		finally{
			query.closeAll();
			pm.close();
		}
	}

	@Override
	public List<Message> getMessageFrom(String User) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query= pm.newQuery(com.tomcov.shared.Message.class);
		query.setFilter("From == userNameParam && deletefrom == deletefromParam");
		query.setOrdering("date desc");
		query.declareParameters("String userNameParam, String deletefromParam");
		try{
			@SuppressWarnings("unchecked")
			List<Message> results = (List<Message>) query.execute(User,"false");
			return (List<Message>) pm.detachCopyAll(results);

		}
		finally{
			query.closeAll();
			pm.close();
		}
	}

	@Override
	public Message delete(Message message) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(com.tomcov.shared.Message.class);
		query.setFilter("deletefrom == deletefromParam && deleteto == deletetoParam");
		query.declareParameters("String deleteParam, String deletetoParam");

		try{
			@SuppressWarnings("unchecked")
			List<Message> results = (List<Message>) query.execute("true","true");
			if(results.size()==0){
				return null;
			}
			else{
				for(int i=0;i<results.size();i++){
					Message res= results.get(i);
					pm.deletePersistent(res);
				}
				
				return results.get(0);
			}
		}
		finally{
			query.closeAll();
			pm.close();
		}
	}

	public Message update(Message message, int i){
	PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
    	Message e = pm.getObjectById(com.tomcov.shared.Message.class, message.getId());
    	if(i==1){e.setDeleteto("true");return e;}
    	else if(i==2){e.setDeletefrom("true");return e;}
    	else return e;
    }
    finally{
    	pm.close();
    }
}


}
